package com.hz.friends.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.hz.friends.chat.Helper.CCPConfig;
import com.hz.friends.chat.Helper.CCPHelper;
import com.hz.friends.chat.Helper.CCPUtil;
import com.hz.friends.fragment.BaseFragment;
import com.hz.friends.fragment.MessageFragment;
import com.hz.friends.fragment.SetupFragment;
import com.hz.friends.fragment.contacts.ContactsFragment;
import com.hz.friends.fragment.nearby.NearbyFragment;
import com.hz.friends.global.Global;
import com.hz.friends.serverrequest.ALCCPEngine;
import com.hz.friends.serverrequest.ALEngineConfig;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.MLog;

public class MaintabsActivity extends BaseFragmentActivity implements
		OnClickListener {

	private ImageView imv_nearby; // 附近
	private ImageView imv_contact;// 联系人
	private ImageView imv_message;// 消息
	private ImageView imv_setting;// 设置
	private TextView txv_bubble_nearby;// 附近气泡
	private TextView txv_bubble_message;// 消息气泡
	private ViewPager viewpage;
	// private MainFragmentPagerAdapter paageadpter;
	private FragmentViewPagerAdapter pageadpter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initViews();
		initEvents();
		init();
		ALCCPEngine.clear();
	}

	// guokr002 111111

	protected void init() {
		// mhandler.postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// CCPHelper.getInstance().initVoipDevice();
		// }
		// }, 2000);

	}

	protected void initViews() {

		imv_nearby = (ImageView) findViewById(R.id.imv_nearby); // 附近
		imv_contact = (ImageView) findViewById(R.id.imv_contact); // 联系人
		imv_message = (ImageView) findViewById(R.id.imv_message);// 消息
		imv_setting = (ImageView) findViewById(R.id.imv_setting); // 设置
		txv_bubble_nearby = (TextView) findViewById(R.id.txv_bubble_nearby); // 附近气泡
		txv_bubble_message = (TextView) findViewById(R.id.txv_bubble_message);// 消息气泡
		Bitmap redbitmap = BitmapUtils.drawCycleImage("#ff4948", getResources()
				.getDimensionPixelSize(R.dimen.mai_bottom_bubble));
		txv_bubble_nearby.setBackgroundDrawable(new BitmapDrawable(redbitmap));
		txv_bubble_message.setBackgroundDrawable(new BitmapDrawable(redbitmap));

		viewpage = (ViewPager) findViewById(R.id.viewPager);

		List<BaseFragment> fragments = new ArrayList<BaseFragment>();
		final BaseFragment nearbyfragment = new NearbyFragment();
		final BaseFragment contactsfragment = new ContactsFragment();
		BaseFragment messagefragment = new MessageFragment();
		BaseFragment setupfragment = new SetupFragment();
		fragments.add(nearbyfragment);
		fragments.add(contactsfragment);
		fragments.add(messagefragment);
		fragments.add(setupfragment);
		//
		// paageadpter = new
		// MainFragmentPagerAdapter(getSupportFragmentManager(),
		// fragments);
		// viewpage.setAdapter(paageadpter);
		//
		pageadpter = new FragmentViewPagerAdapter(getSupportFragmentManager(),
				viewpage, fragments);
		viewpage.setAdapter(pageadpter);

		mhandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				nearbyfragment.initDatas();
			}
		}, 1000);

	}

	protected void initEvents() {
		findViewById(R.id.layout_nearby).setOnClickListener(this);
		findViewById(R.id.layout_contact).setOnClickListener(this);
		findViewById(R.id.layout_message).setOnClickListener(this);
		findViewById(R.id.layout_setting).setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.layout_nearby: // 附近
			setTabsDefalutIcon();
			imv_nearby.setImageResource(R.drawable.ic_tab_nearby2);
			viewpage.setCurrentItem(0, false);
			break;
		case R.id.layout_contact: // 联系人

			setTabsDefalutIcon();
			imv_contact.setImageResource(R.drawable.ic_tab_contact2);
			viewpage.setCurrentItem(1, false);
			pageadpter.getItemFragment(1).initDatas();
			break;
		case R.id.layout_message:// 消息

			setTabsDefalutIcon();
			imv_message.setImageResource(R.drawable.ic_tab_message2);
			viewpage.setCurrentItem(2, false);
			break;
		case R.id.layout_setting:// 设置

			setTabsDefalutIcon();
			imv_setting.setImageResource(R.drawable.ic_tab_setting2);
			viewpage.setCurrentItem(3, false);
			break;
		default:
			break;
		}
	}

	private Handler mhandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:

				break;
			case 2:

				break;
			case 3:

				break;
			case 4:

				break;
			default:
				break;
			}
		};
	};

	// 底部类别按钮设置为默认图标
	private void setTabsDefalutIcon() {
		imv_contact.setImageResource(R.drawable.ic_tab_contact1);
		imv_nearby.setImageResource(R.drawable.ic_tab_nearby1);
		imv_message.setImageResource(R.drawable.ic_tab_message1);
		imv_setting.setImageResource(R.drawable.ic_tab_setting1);

	}

	// public class MainFragmentPagerAdapter extends FragmentPagerAdapter {
	// private List<Fragment> fragments;
	//
	// public MainFragmentPagerAdapter(FragmentManager fm) {
	// super(fm);
	// }
	//
	// public MainFragmentPagerAdapter(FragmentManager fm,
	// List<Fragment> fragments) {
	// super(fm);
	// this.fragments = fragments;
	// }
	//
	// /*
	// * (non-Javadoc)
	// *
	// * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
	// */
	// @Override
	// public Fragment getItem(int arg0) {
	// return fragments.get(arg0);
	// }
	//
	// /*
	// * (non-Javadoc)
	// *
	// * @see android.support.v4.view.PagerAdapter#getCount()
	// */
	// @Override
	// public int getCount() {
	// return fragments.size();
	// }
	//
	// @Override
	// public int getItemPosition(Object object) {
	// // TODO Auto-generated method stub
	// return super.getItemPosition(object);
	// }
	// }

	/**
	 * 为ViewPager添加布局（Fragment），绑定和处理fragments和viewpager之间的逻辑关系
	 * http://www.cnblogs.com/tiantianbyconan/p/3364728.html Created with
	 * IntelliJ IDEA. Author: wangjie email:tiantian.china.2@gmail.com Date:
	 * 13-10-11 Time: 下午3:03
	 */
	class FragmentViewPagerAdapter extends PagerAdapter implements
			ViewPager.OnPageChangeListener {
		private List<BaseFragment> fragments; // 每个Fragment对应一个Page
		private FragmentManager fragmentManager;
		private ViewPager viewPager; // viewPager对象
		private int currentPageIndex = 0; // 当前page索引（切换之前）

		private OnExtraPageChangeListener onExtraPageChangeListener; // ViewPager切换页面时的额外功能添加接口

		public FragmentViewPagerAdapter(FragmentManager fragmentManager,
				ViewPager viewPager, List<BaseFragment> fragments) {
			this.fragments = fragments;
			this.fragmentManager = fragmentManager;
			this.viewPager = viewPager;
			this.viewPager.setAdapter(this);
			this.viewPager.setOnPageChangeListener(this);
		}

		@Override
		public int getCount() {
			return fragments.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object o) {
			return view == o;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(fragments.get(position).getView()); // 移出viewpager两边之外的page布局
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			Fragment fragment = fragments.get(position);
			if (!fragment.isAdded()) { // 如果fragment还没有added
				FragmentTransaction ft = fragmentManager.beginTransaction();
				ft.add(fragment, fragment.getClass().getSimpleName());
				ft.commit();
				/**
				 * 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
				 * 会在进程的主线程中，用异步的方式来执行。 如果想要立即执行这个等待中的操作，就要调用这个方法（只能在主线程中调用）。
				 * 要注意的是，所有的回调和相关的行为都会在这个调用中被执行完成，因此要仔细确认这个方法的调用位置。
				 */
				fragmentManager.executePendingTransactions();
			}

			if (fragment.getView().getParent() == null) {
				container.addView(fragment.getView()); // 为viewpager增加布局
			}

			return fragment.getView();
		}

		public BaseFragment getItemFragment(int postion) {
			return fragments.get(postion);
		}

		/**
		 * 当前page索引（切换之前）
		 * 
		 * @return
		 */
		public int getCurrentPageIndex() {
			return currentPageIndex;
		}

		public OnExtraPageChangeListener getOnExtraPageChangeListener() {
			return onExtraPageChangeListener;
		}

		/**
		 * 设置页面切换额外功能监听器
		 * 
		 * @param onExtraPageChangeListener
		 */
		public void setOnExtraPageChangeListener(
				OnExtraPageChangeListener onExtraPageChangeListener) {
			this.onExtraPageChangeListener = onExtraPageChangeListener;
		}

		@Override
		public void onPageScrolled(int i, float v, int i2) {
			if (null != onExtraPageChangeListener) { // 如果设置了额外功能接口
				onExtraPageChangeListener.onExtraPageScrolled(i, v, i2);
			}
		}

		@Override
		public void onPageSelected(int i) {
			fragments.get(currentPageIndex).onPause(); // 调用切换前Fargment的onPause()
			// fragments.get(currentPageIndex).onStop(); //
			// 调用切换前Fargment的onStop()
			if (fragments.get(i).isAdded()) {
				// fragments.get(i).onStart(); // 调用切换后Fargment的onStart()
				fragments.get(i).onResume(); // 调用切换后Fargment的onResume()
			}
			currentPageIndex = i;

			if (null != onExtraPageChangeListener) { // 如果设置了额外功能接口
				onExtraPageChangeListener.onExtraPageSelected(i);
			}

		}

		@Override
		public void onPageScrollStateChanged(int i) {
			if (null != onExtraPageChangeListener) { // 如果设置了额外功能接口
				onExtraPageChangeListener.onExtraPageScrollStateChanged(i);
			}
		}

		/**
		 * page切换额外功能接口
		 */
		class OnExtraPageChangeListener {
			public void onExtraPageScrolled(int i, float v, int i2) {
			}

			public void onExtraPageSelected(int i) {
			}

			public void onExtraPageScrollStateChanged(int i) {
			}
		}

	}

	@Override
	public void onBackPressed() {
		// super.onBackPressed();
		exitSoft();
	}

	private void exitSoft() {
		new AlertDialog.Builder(this).setTitle("提示").setMessage("是否退出软件")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						ALCCPEngine.clear();
						CCPUtil.exitCCPDemo();
						Intent exitintent = new Intent(
								Global.INTETN_ACTION_EXIT_SOFT);
						sendBroadcast(exitintent);
						finish();
					}
				}).setNegativeButton("取消", null).create().show();
	}

	@Override
	protected void setViews() {
		// TODO Auto-generated method stub

	}
    /**
     * 设置未读消息数
     * @param count
     */
	public void setMessageBubbleCount(int count){
		if(count >0){
			txv_bubble_message.setText(String.valueOf(count));
			txv_bubble_message.setVisibility(View.VISIBLE);
		}else{
			txv_bubble_message.setVisibility(View.INVISIBLE);
		}
	}
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		MLog.i(TAG, "====Maintabsactivity  onActivityResult" + arg0);
		super.onActivityResult(arg0, arg1, arg2);
	}
}
